package cn.shengchao.examstar.knowledge.application;

import cn.shengchao.examstar.knowledge.acl.adapters.StudyPlanAdapter;
import cn.shengchao.examstar.knowledge.acl.dto.KnowledgePointMasteryDTO;
import cn.shengchao.examstar.knowledge.domain.vo.MasteryStatusEnum;
import cn.shengchao.examstar.shared.acl.ai.AIKnowledgeEvaluationService;
import cn.shengchao.examstar.shared.acl.ai.dto.KnowledgeEvaluationResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 练习相关应用服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExerciseApplicationService {

    private final StudyPlanAdapter studyPlanAdapter;

    @Autowired
    private AIKnowledgeEvaluationService aiKnowledgeEvaluationService;


    /**
     * 更新知识点掌握度状态
     *
     * @param userId 用户ID
     * @param knowledgePointId 知识点ID
     * @param statusEnum 状态枚举
     * @return 更新后的知识点掌握度
     */
    public KnowledgePointMasteryDTO updateKnowledgePointMasteryStatus(Long userId, Long knowledgePointId,
                                                                      MasteryStatusEnum statusEnum) {

        log.info("更新知识点掌握度状态(枚举): 用户ID={}, 知识点ID={}, 状态={}",
                userId, knowledgePointId, statusEnum);

        return studyPlanAdapter.updateMasteryStatus(userId, knowledgePointId, statusEnum);
    }

    /**
     * 根据AI工作流评估结果批量更新知识点掌握度
     *
     * @param userId 用户ID
     * @param exerciseData 做题数据JSON
     * @return 更新后的知识点掌握度列表
     */
    public List<KnowledgePointMasteryDTO> batchUpdateKnowledgePointMasteryByWorkflow(
            Long userId, String exerciseData) throws IOException {

        log.info("开始批量更新知识点掌握度 - 用户ID: {}", userId);

        // 1. 调用AI服务，获取知识点掌握度评估
        KnowledgeEvaluationResult evaluation =
                aiKnowledgeEvaluationService.evaluateKnowledgeMastery(userId, exerciseData);

        // 2. 遍历评估结果，批量更新知识点掌握度
        List<KnowledgePointMasteryDTO> updatedMasteries = new ArrayList<>();

        for (KnowledgeEvaluationResult.KnowledgePointEvaluation item : evaluation.getKnowledgePointEvaluations()) {
            try {
                // 转换知识点ID为Long类型
                Long knowledgePointId = Long.parseLong(item.getKnowledgePointId());

                // 获取准确率
                String accuracyRate = item.getAccuracyRate();

                // 获取掌握程度
                String degreeOfMastery = item.getDegreeOfMastery();

                // 1. 先更新准确率和掌握程度
                KnowledgePointMasteryDTO updatedMastery = studyPlanAdapter.updateMasteryFromExercise(
                        userId, knowledgePointId, accuracyRate, degreeOfMastery,null);
                // 添加到结果列表
                updatedMasteries.add(updatedMastery);

                log.info("更新知识点掌握度成功 - 知识点ID: {}, 掌握程度: {}, 准确率: {}",
                        knowledgePointId, degreeOfMastery, accuracyRate);
            } catch (Exception e) {
                log.error("更新知识点掌握度失败 - 知识点ID: {}", item.getKnowledgePointId(), e);
            }
        }

        log.info("批量更新知识点掌握度完成 - 用户ID: {}, 更新数量: {}", userId, updatedMasteries.size());

        return updatedMasteries;
    }

    /**
     * 获取知识点掌握度状态
     * 根据业务需求，当通过AI评估更新掌握度时，将状态设置为"练习中"
     */
    private MasteryStatusEnum getMasteryStatus() {
        return MasteryStatusEnum.SUMMARY;
    }
} 